//
//  SearchViewController.m
//  TeacherNet
//
//  Created by slz on 2017/12/14.
//  Copyright © 2017年 bnsr. All rights reserved.
//

#import "SearchViewController.h"
#import "CourseTableViewCell.h"
#import "CourseDetailViewController.h"

@implementation SearchPageModel
+ (NSDictionary *)modelContainerPropertyGenericClass {
    return @{@"searchResultList" : [CourseModel class],
             };
}

+ (NSDictionary *)modelCustomPropertyMapper {
    return @{@"searchResultList" : @"searchList"
             };
}
@end

@interface SearchNavigationView : UIView
@property (nonatomic,strong) UISearchBar *searchBar;
@property (nonatomic,strong) UIButton *cancleButton;
@end

@implementation SearchNavigationView
- (instancetype)init
{
    self = [super init];
    if (self){
        UIView * lineView = [UIView new];
        lineView.backgroundColor = kLight_TextColor_Default;
        [self addSubview:lineView];
        [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.leading.trailing.and.bottom.mas_equalTo(self);
            make.height.mas_equalTo(.5);
        }];
        
        
        _searchBar = [UISearchBar new];
        _searchBar.placeholder = @"搜索课程名称";
        _searchBar.searchBarStyle = UISearchBarStyleMinimal;
        _searchBar.returnKeyType = UIReturnKeySearch;
        _searchBar.barTintColor = [UIColor whiteColor];
        [self addSubview:_searchBar];
        [_searchBar mas_makeConstraints:^(MASConstraintMaker *make) {
            make.leading.mas_equalTo(10);
            make.right.mas_equalTo(self.mas_right).offset(-50);
            make.bottom.mas_equalTo(self.mas_bottom).offset(-5);
            make.height.mas_equalTo(44);
        }];
        
        
        _cancleButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_cancleButton setTitle:@"取消" forState:UIControlStateNormal];
        _cancleButton.titleLabel.fontSize = kFont_Size_Cotent_Nomal;
        [_cancleButton setTitleColor:kDark_TextColor_Default forState:UIControlStateNormal];
        [self addSubview:_cancleButton];
        [_cancleButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.mas_equalTo(self.mas_right).offset(-10);
            make.centerY.mas_equalTo(_searchBar.mas_centerY);
            make.size.mas_equalTo(CGSizeMake(40, 44));
        }];
        
      
        
       
        UITextField *searchTextField = [self.searchBar valueForKey:@"_searchField"];
        if ([searchTextField respondsToSelector:@selector(setAttributedPlaceholder:)]) {
            UIFont *font = [UIFont systemFontOfSize:15];
            searchTextField.font = font;
            searchTextField.textColor = kDark_TextColor_Default;
            searchTextField.backgroundColor =  [UIColor colorWithRed:230 green:230 blue:230 alpha:.7];
            for (id subView in searchTextField.subviews) {
                if ([subView isKindOfClass:NSClassFromString(@"_UISearchBarSearchFieldBackgroundView")]){
                    if ([subView isKindOfClass:[UIImageView class]]){
                        ((UIImageView *)subView).image = [UIImage imageNamed:@"search_back"];
                    }
                }
                if ([subView isKindOfClass:NSClassFromString(@"UISearchBarBackground")]){
                    ((UIImageView *)subView).image = [UIImage imageWithColor:[UIColor whiteColor]];
                }
            }
        }
    }
        
    return self;
}
@end

@interface SearchViewController ()<UISearchBarDelegate,UITableViewDelegate,UITableViewDataSource,UISearchBarDelegate>
@property (nonatomic,strong) SearchNavigationView *navView;
@property (nonatomic,strong) YWTableView *tableView;
@property (nonatomic,strong) SearchPageModel * pageModel;
@property (nonatomic,strong) UILabel *noDataLabel;
@end

@implementation SearchViewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self.navView.searchBar becomeFirstResponder];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.showNavigationBar = NO;
    self.navigationItem.hidesBackButton = YES;
    _navView = [SearchNavigationView new];
    [self.view addSubview:_navView];
    [_navView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.and.top.mas_equalTo(self.view);
        make.height.mas_equalTo(self.customNavigationHeight);
    }];
    _navView.searchBar.delegate = self;
    
    @weakify(self);
    [_navView.cancleButton addBlockForControlEvents:UIControlEventTouchUpInside block:^(id  _Nonnull sender) {
        [weak_self.navigationController popViewControllerAnimated:YES];
    }];
    
    _tableView = [[YWTableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        @strongify(self);
        [self seachrWithkeyWord:self.navView.searchBar.text];
    }];
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.and.bottom.mas_equalTo(self.view);
        make.top.mas_equalTo(_navView.mas_bottom);
    }];
    
    _noDataLabel = [UILabel new];
    _noDataLabel.hidden = YES;
    _noDataLabel.text = @"未搜索到相关课程~";
    _noDataLabel.textAlignment = NSTextAlignmentCenter;
    _noDataLabel.textColor = kDark_TextColor_Default;
    _noDataLabel.fontSize = kFont_Size_Big_Title;
    [self.view addSubview:_noDataLabel];
    [_noDataLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view.mas_centerX);
        make.top.mas_equalTo(_navView.mas_bottom).offset(50);
    }];
}

- (void)seachrWithkeyWord:(NSString *)keyword
{
    if (!keyword || keyword.length == 0)
    {
        [_tableView.mj_header endRefreshing];
        return;
    }
    [BaseHttpTool get:kAPI_SEARCH params:@{@"str":keyword} success:^(id responseObj) {
        [_tableView.mj_header endRefreshing];
        NSDictionary * dict = [[MFWJson jsonWithObject:responseObj] toDic];
        _pageModel = [SearchPageModel yy_modelWithDictionary:dict];
        [_tableView  reloadData];
        [self handleSearchResult];
    } failure:^(NSError *error) {
        [_tableView.mj_header endRefreshing];
        [self.view showTip:error.localizedDescription];
    }];
}


- (void)handleSearchResult
{
    if (_pageModel.searchResultList.count == 0){
        [self showTiplabel];
    }else{
        self.tableView.hidden = NO;
        self.noDataLabel.hidden = YES;
    }
}

- (void)showTiplabel
{
    [UIView animateWithDuration:.5 animations:^{
        self.noDataLabel.hidden = NO;
        self.tableView.hidden = YES;
    }];
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * reuserIndentifier = @"CourseTableViewCell";
    CourseTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:reuserIndentifier];
    if (!cell){
        cell = [[CourseTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuserIndentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    CourseModel * model = _pageModel.searchResultList[indexPath.row];
    [cell.courseImageView sd_setImageWithURL:[NSURL URLWithString:kAPI_IMAGE_HOST(model.courseImage)] randomPlaceHolder:YES];
    cell.courseName.text = model.courseName;
    cell.coursePrice.text = [NSString stringWithFormat:@"%@%@",@"¥",model.coursePrice];
    cell.courseTeacher.text = model.courseTeacher;
    cell.courseStudentCount.text = model.studentCount;
    cell.courseTeacherTitle.text = model.courseTeacherTitle;
    return cell;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _pageModel.searchResultList.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 80;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    CourseModel * model = _pageModel.searchResultList[indexPath.row];
    if (model.courseId && model.courseId.length > 0){
        CourseDetailViewController * detailController = [CourseDetailViewController new];
        detailController.courseId = model.courseId;
        [self.navigationController pushViewController:detailController animated:YES];
    }
}

-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    NSString * keyword = searchBar.text;
    if (!keyword || keyword.length == 0)
    {
        return;
    }
    self.tableView.hidden = NO;
    self.noDataLabel.hidden = YES;
    [self.tableView.mj_header beginRefreshing];
}


- (void)backClicked{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
